﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Interface;
using NetDon.OA.Interface.Admin;
using NetDon.Utilities;
using NetDon.WebControls;

namespace NetDon.OA.Portal.Components
{
    public partial class UserSearchPopup : PageBase
    {
        #region Properties

        string QueryMode
        {
            get { return Parameters.GetString("Mode"); }
        }

        Guid? CompanyId
        {
            get
            {
                return treeOrganization.CompanyId;
            }
        }

        Guid DepartmentId
        {
            get
            {
                return treeOrganization.DepartmentId;
            }
        }

        #endregion

        #region Control Event Handler

        protected void Page_Load(object sender, EventArgs e)
        {
            treeOrganization.LoadItems += this.btnModify_Click;
          
            if (!IsPostBack)
            {
               if(QueryMode.ToLower() =="single")
               {
                   this.gridUsers.Columns[0].Visible = false;
                   this.gridUsers.Columns[1].Visible = true;
               }
               else if (QueryMode.ToLower() == "template")
               {
               }
               else
               {
                   this.gridUsers.Columns[0].Visible = true;
                   this.gridUsers.Columns[1].Visible = false;
               }
                CancelButton = btnCancel;
                PagerUsers.PageSize = 20;
                dplUserStatus.SelectedValue = UserStatus.Active.ToString();
                PagerUsers.PerformQuery();
            }
        }

        protected void PagerUsers_PerformGetPageData(object sender, PerformGetPageDataEventArgs e)
        {
            var service = ServiceContainer.GetService<IUserService>();
            e.DataSource = service.SearchUsers(
                (UserSearchCriteria)e.Condition,
                gridUsers.SortExpression,
                gridUsers.SortDirection,
                e.PageSize,
                e.PageIndex
                );
        }

        protected void PagerUsers_PerformGetRecordCount(object sender, PerformGetRecordCountEventArgs e)
        {
            var service = ServiceContainer.GetService<IUserService>();
            e.RecordCount = service.GetUserCount((UserSearchCriteria)e.Condition);
        }

        protected void PagerUsers_PerformGetCondition(object sender, PerformGetConditionEventArgs e)
        {
            var criteria = new UserSearchCriteria
            {
                UserName = txtLoginName.Text.Trim(),
                Email = txtEmail.Text.Trim(),
                FullName = txtFullName.Text.Trim()
            };

            if (!string.IsNullOrEmpty(dplUserType.SelectedValue))
            {
                criteria.UserType = dplUserType.SelectedValue.ToEnum<UserType>();
            }

            if (!string.IsNullOrEmpty(dplUserStatus.SelectedValue))
            {
                criteria.Status = dplUserStatus.SelectedValue.ToEnum<UserStatus>();
            }

            if (CompanyId.HasValue && CompanyId.Value != Guid.Empty)
            {
                criteria.CompanyId = CompanyId;
            }

            if (DepartmentId != Guid.Empty)
            {
                criteria.DepartId = DepartmentId;
            }

            e.Condition = criteria;
        }


        protected void btnSearch_Click(object sender, EventArgs e)
        {
            PagerUsers.PerformQuery();
        }
        protected void gridUsers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var entity = (e.Row.DataItem);
                if (entity != null)
                {
                    e.Row.Attributes["UserId"] = Convert.ToString(DataBinder.Eval(entity, "UserId"));
                    e.Row.Attributes["FullName"] = Convert.ToString(DataBinder.Eval(entity, "FullName"));
                    e.Row.Attributes["UserName"] = Convert.ToString(DataBinder.Eval(entity, "UserName"));
                    e.Row.Attributes["DepartId"] = Convert.ToString(DataBinder.Eval(entity, "DepartId"));
                    e.Row.Attributes["DepartName"] = Convert.ToString(DataBinder.Eval(entity, "DepartName"));
                }
            }
        }

        protected void btnReload_Click(object sender, EventArgs e)
        {
            PagerUsers.PerformQuery();
        }

        protected void btnModify_Click(object sender, EventArgs e)
        {
            PagerUsers.PerformQuery();
        }

        protected void radioSelected_CheckedChanged(object sender, EventArgs e)
        {
            var rdb = sender as RadioButton;

            foreach (GridViewRow row in gridUsers.Rows)
            {
                var radioButton = row.FindControl("radioSelected") as RadioButton;
                if (radioButton == rdb) continue;
                radioButton.Checked = false;
            }
        }

        public IList<UserEntity> CheckItemSelection()
        {
            var selectedUsers = new List<UserEntity>();
            if (QueryMode.ToLower() =="single")
            {
                foreach (GridViewRow row in gridUsers.Rows)
                {
                    var radioButton = (RadioButton)row.FindControl("radioSelected");
                    if (radioButton != null)
                    {
                        if (radioButton.Checked)
                        {
                            var userId = row.Attributes["UserId"].ToGuid();
                            var fullName = (row.Attributes["FullName"]);
                            var userName = (row.Attributes["UserName"]);
                            var departId = (row.Attributes["DepartId"]);
                            var departName = (row.Attributes["DepartName"]);
                            selectedUsers.Add(new UserEntity()
                            {
                                UserId = userId,
                                FullName = fullName,
                                UserName = userName,
                                DepartmentId =departId,
                                DepartmentName =departName
                            });
                        }
                    }
                }
            }
            else
            {
                foreach (GridViewRow row in gridUsers.Rows)
                {
                    var chkSelected = (CheckBox)row.FindControl("chkSelect");
                    if (chkSelected != null)
                    {
                        if (chkSelected.Checked)
                        {
                            var userId = row.Attributes["UserId"].ToGuid();
                            var fullName = (row.Attributes["FullName"]);
                            var userName = (row.Attributes["UserName"]);
                            var departId = (row.Attributes["DepartId"]);
                            var departName = (row.Attributes["DepartName"]);
                            selectedUsers.Add(new UserEntity()
                            {
                                UserId = userId,
                                FullName = fullName,
                                UserName = userName,
                                DepartmentId = departId,
                                DepartmentName = departName
                            });
                        }
                    }
                }
            }
        
            return selectedUsers;
        }

        protected void btnChoose_Click(object sender, EventArgs e)
        {
            var selectedUsers = CheckItemSelection();
            if (selectedUsers.Count > 0)
            {
                var serializer = new DataContractJsonSerializer(typeof(IList<UserEntity>));
                var stream = new MemoryStream();
                serializer.WriteObject(stream, selectedUsers);
                stream.Position = 0;
                var sr = new StreamReader(stream);
                string resultStr = sr.ReadToEnd();
                sr.Close();
                stream.Close();
                CloseWindow(resultStr);
            }
            else
            {
                base.Alert("请选择用户.");
                return;
            }

        }

        #endregion
    }

    [DataContract]
    public class UserEntity
    {
        [DataMember]
        public Guid UserId { get; set; }
        [DataMember]
        public string FullName { get; set; }
        [DataMember]
        public string UserName { get; set; }
        [DataMember]
        public string DepartmentId { get; set; }
        [DataMember]
        public string DepartmentName { get; set; }
    }
}